<template>
  <div class="top-bar" ref="top" :class="[!hasBack && !hasClose ? 'center' : 'between', (white && !scrollTop) ? 'white': '', ( bg && !scrollTop ? 'bg' : '' )]">
		<div class="left">
			<div v-if="!hasClose" class="icon back" @click="goBack">
				<van-icon name="arrow-left" />
			</div>
			<div v-if="hasClose" class="icon close" @click="goBack">
				<van-icon name="cross" />
			</div>
		</div>
    <span class="center">{{ pageTitle }}</span>
    <div class="right">
			<slot></slot>
		</div>
  </div>
</template>
<script>
import Vue from 'vue';
import { Icon } from 'vant';
Vue.use(Icon);
export default {
  name: 'TopBar',
  props: {
    title: { type: String, default: '' },
    hasBack: { type: Boolean, default: false },
    onBack: { type: Function, default: null },
    hasClose: { type: Boolean, default: false },
		white: { type: Boolean, default: false },
		bg: { type: Boolean, default: false },
  },
  data() {
    return {
			pageTitle: '',
			scrollTop: false
		}
  },
  watch: {
		title(newV, oldV){
			this.pageTitle = newV;
		}
  },
	mounted(){
		let p = this.$refs.top.parentElement;
		p.onscroll = (e) => {
			if(e.target.scrollTop > 15){
				this.scrollTop = true;
			}else{
				this.scrollTop = false;
			}
		}
	},
	created(){
		if(this.$route.meta){
			this.pageTitle = this.title || this.$route.meta.title || ""
		}
	},
  methods: {
    goBack() {
			if(this.onBack){
				let p = this.onBack();
				if(p === false){
					return;
				}else if(p instanceof Promise){
					p.then(e=>{
						this.$router.go(-1);
					})
				}else{
      		this.$router.go(-1);
				}
			}
      this.$router.go(-1);
    },
	close() {
		debugger;
	}
  }
}
</script>

<style lang="scss" scoped>
	.top-bar {
		display: flex;
		align-items: center;
		position: absolute;
		top: 0;
		width: 100%;
		height: 70px;
		// padding: 0 10px;
		padding-top: 25px;
		font-weight: 500;
		font-size: 21px;
		color: #3D3E54;
		box-sizing: border-box;
		justify-content: space-between;
		background-color: #fff;
		z-index: 2;
		transition: all .15s;
    	border-bottom: 1px solid #F2F1F8;
		&.white{
			color: #FFFFFF;
			background-color: transparent;
    		border-bottom: 1px solid transparent;
		}
		&.bg{
			background-color: #F2F1F8;
    		border-bottom:1px solid #F2F1F8;
		}
		.center{
			line-height: 42px;
		}
		.icon{
			display: flex;
			align-items: center;
			min-width: 40px;
			min-height: 40px;
			font-size: 24px;
		}
		.left,
		.right{
			display: flex;
			align-items: center;
			width: 65px;
			height: 45px;
			padding: 0 10px;
		}
		.right{
			justify-content: flex-end;
			font-size: 16px;
		}
	}
	
</style>
